import CheckDialog from "../components/CheckDialog";
import ApplicationDialog from "../components/ApplicationDialog";
import DiagnosisDialog from "../components/DiagnosisDialog";
import HealthDialog from "../components/HealthDialog";
import DrugDialog from "@/components/chatroom/drug-dialog";
import HisDialog from "../components/HisDialog";
import myImageUpload from "@/components/image-upload/image-upload";
import UpdatePatientDialog from "../components/UpdatePatientInfoDialog";
import UpdateDisease from "../components/DiseaseDialog";
import DrAdviceDialog from "../components/DrAdviceDialog";
import caseHistory from "@/components/case-history";
import pdfDialog from "@/components/chatroom/view-pdf";
import hospitalAdvice from "@/components/chatroom/hospital-advice";
import TrtcVideo from "../components/TrtcVideo.vue";
import AgoraVideo from "../components/AgoraVideo.vue";
import ApplyConsultation from '../../remoteConsult/myConsult/apply.vue'

export default {
  inject: ["reload"], //注入App里的reload方法
  components: {
    "check-dialog": CheckDialog,
    "application-dialog": ApplicationDialog,
    "diagnosis-dialog": DiagnosisDialog,
    "health-dialog": HealthDialog,
    "drug-dialog": DrugDialog,
    "update-patient-dialog": UpdatePatientDialog,
    myImageUpload,
    UpdateDisease,
    DrAdviceDialog,
    caseHistory,
    pdfDialog,
    hospitalAdvice,
    TrtcVideo,
    AgoraVideo,
    HisDialog,
    ApplyConsultation
  },

  data() {
    return {
      isVedioOrPic: "", //图文还是视频问诊
      logId: null, //本次问诊Id
      inquiryPatientId: null, //此次患者id

      friendId: null, // 接收方-患者id
      userImId: null, // 发送方-医生id
      webSocketMsg: {},

      patientList: {}, //患者详情
      patientDetailList: {}, // socket问诊患者详情

      firstVisit: 0, // 患者是否首诊
      finishLoading: false, // 结束问诊loading

      /* 候诊列表 */
      onlineChange: {
        allBtn: "",
        onlineBtn: "",
        outlineBtn: ""
      },
      filterBar: [
        { name: "全部", type: "2" },
        { name: "在线", type: "1" },
        { name: "离线", type: "0" }
      ],
      changeBtn: "1",
      lineUpPatientList: [], // 候诊患者

      /* 聊天窗 */
      sendMsgToPatient: "", // 聊天信息
      chatRoomMsgList: [], //聊天记录
      noHistoryChat: false, // 是否存在聊天记录
      quickMsglist: [], // 快捷回复列表
      popoverMsg: false, // 快捷回复下拉菜单
      /* 撤回 */
      isWithdraw: false,
      msgData: {},
      top: 0,
      left: 0,

      /* 测量数据 */
      measuredDataDialog: false, //测量数据弹框
      measuredList: [], //测量数据列表
      measuredListPage: {
        //测量数据分页
        total: 0,
        current: 1,
        size: 50
      },

      /* 主诉、现病史、既往史、过敏史 */
      chiefComplaintDialog: false, //主诉、现病史、既往史弹框
      chiefModelDialog: false, //主诉、现病史、既往史新增模板弹框
      chiefModelForm: {
        //新增主诉、现病史、既往史模板
        templateType: "",
        templateName: "",
        templateDetails: ""
      },
      chiefModelFormRule: {
        //新增主诉、现病史、既往史模板
        templateType: [
          { required: true, message: "模板类型不能为空", trigger: "change" }
        ],
        templateName: [
          { required: true, message: "模板名称不能为空", trigger: "blur" }
        ],
        templateDetails: [
          { required: true, message: "模板内容不能为空", trigger: "blur" }
        ]
      },
      chiefComplaintName: "1", //主诉、现病史、既往史--tab
      chiefDialog: {
        chiefInput: "",
        nowInput: "",
        pastInput: ""
      },
      chiefModelName: "0", //主诉、现病史、既往史--公用和个人模板
      templateNameSearch: "", //主诉、现病史、既往史--公用和个人模板--搜索
      complaintTemplateList: [], //主诉、现病史、既往史--公用和个人模板--列表
      modelId: null, //编辑模板的id
      /* 过敏史 */
      allergyHistoryDialog: false, //过敏史弹框
      isAllergy: "", //是否有过敏史
      isAllergyInput: "", //有过敏史的输入框
      allergyLoading: false, //过敏史加载
      /*孕/哺乳*/
      childOptionDialog: false,
      /* 查看+发送图片 */
      sendPicDialog: false, //发送图片弹框
      picDataDialog: false, //查询图片弹框
      imageUrl: "",
      ossParams: "",
      sendPicLoading: false,
      isLeave: false, //定义变量判断是否还停留在当前此页面中
      refreshData: null, //定时器定义变量

      /* 住院建议 */
      proposalDataDialog: false, //住院建议书弹框
      isOpenProposal: false, //是否开了住院建议书
      proposalForm: {
        hospitalizationDepartment: "",
        remark: ""
      },
      proposalFormRule: {
        hospitalizationDepartment: [
          { required: true, message: "科室不能为空", trigger: "blur" }
        ]
      },

      /* 人体示意图 */
      bodySignDialog: false, //人体示意弹框

      /* 结束问诊 */
      finishDataDialog: false, //结束问诊弹框
      finishInquiryDialog: false, //用户结束问弹框--packageType=14
      isOutline: false, //用户下线提示弹框

      /* 问诊规范*/
      standardDetailDialog: false, //药品规范查看弹框
      drugSpeciFicationDetailDialog: false, //药品规范详情弹框
      standardDataDialog: false, //问诊规范弹框
      standardPage: {
        //问诊规范分页
        total: 0,
        current: 1,
        size: 5
      },
      standardActiveName: "1",
      standardSearch: "", //问诊规范搜索
      standardList: [], //问诊规范列表
      standardDrugList: [], //药品规范
      standardDrugSearch: "", //药品搜索
      standardDrugDetailList: {}, //药品查看列表
      standardDrugPage: {
        //药品规范分页
        total: 0,
        current: 1,
        size: 50
      },
      ficationDetailList: {}, //药品规范-详情按钮
      diagnosisList: [], //诊断规范
      standardDiagnosisSearch: "", //诊断搜索
      diagnosisPage: {
        //诊断规范分页
        total: 0,
        current: 1,
        size: 50
      },

      /* 检验检查模块  */
      inspectionDialog: false, //检验检查弹框
      inspectionName: "1", //检验检查tab
      inspectionSearch: "", //检验检查搜索
      inspectionPaneList: [], //检验检查Pane
      inspectionDetailsList: [], //检验检查PaneDetails
      activeNames: ["1"],
      inspectionListId: null, //检验检查tab的id
      chatImages: [], //获取查询图片

      /* 健康指导弹框  */
      chooseICDSearchDialog: false, //健康指导弹框--另存意见单
      healthActiveName: "0", //健康指导tab
      healthSearch: "", //健康指导搜索
      healthDataList: [], //健康指导列表
      healthSaveInput: "", //健康指导--新增个人模板名称input
      healthSaveICDInput: "", //健康指导--新增个人模板诊断input
      healthSaveICDId: null, //健康指导--新增个人模板诊断ID
      healthDetailsInput: "", //健康指导--查看模板input
      viewInquiryLog: [], //健康指导--查看意见单内容
      healthGuidanceList: [], //健康指导--问诊过程中生成的意见单
      doctorHealthGuide: "", //健康指导--医生健康指导内容
      recordEntityData: {
        icdName: " ",
        icdName2: " "
      },
      healthICDSearch: "", //健康指导--icd检索
      ICDlist: [], //icd列表

      /* 中、西药弹框 */
      chineseMedicineDialog: false, // 开药
      addPrescriptionDialog: false, // 开药弹框
      prescriptionInfoListDialog: false, // 历史处方--查看详情
      addPrescriptionTemplateDialog: false, // 另存模板弹框

      isWesternChinese: "", //中药还是西药(1中药 2西药 不传则查全部)
      drugClassSearch: "", //下拉药品类别搜索
      drugClassList: [], //下拉药品搜索
      drugNameSearch: "", //药品列表搜索
      westernDataPage: {
        //药品规范分页
        total: 0,
        current: 1,
        size: 50
      },
      westernModelList: [], //西药个人&公用模板列表
      historyWesternList: [], //历史列表
      openWesternList: [], //已开处方
      historyListLoading: false, //历史列表加载
      prescriptionInfoList: [], //历史列表--查看详情

      /* 分诊 */
      triageLogMsg: {}, //分诊信息
      triageInquiryDialog: false, //分诊弹框
      departmentList: [], //获取科室列表
      departmentNameSearch: "", //科室名字
      doctorNameSearch: "", //医生名字搜索
      onlineDoctorList: [], //医生在线列表
      triagePatientType: null, //分诊单类型
      triageType: null, //分诊单类型
      isChangeMsg: false, //患者是否修改测量数据

      /* 结束问诊 */
      noPrescriptionList: {}, //未开方原因
      finishReasonSearch: "", //未开放原因

      /* 付费类型 */
      paymentLoading: false,
      paymentForm: {
        paymentMethod: ""
      },
      paymentRules: {
        paymentMethods: [
          { required: true, message: "请选择付费类型", trigger: "change" }
        ]
      },
      paymentCfg: {
        visible: false,
        title: "编辑付费类型",
        handles: [
          {
            label: "取消",
            type: "text",
            handle: () => (this.paymentCfg.visible = false)
          },
          { label: "保存", type: "primary", handle: this.submitPaymentForm }
        ]
      },

      /* 待确认字段 */
      ICDTypeName: "", //ICD检索名称
      applyDialog: false, //申请弹框
      applyQuery: {}, //申请弹框参数
    };
  },
  computed: {
    //在computed方法声明并存储到vuex
    getWsMsg() {
      return this.$store.state.webSocketMsg;
    }
  },
  watch: {
    //监听
    getWsMsg(data, val) {
      if (data != "pong" && data != "") {
        //获取医生发送的信息
        if (data.packageType == 3) {
          this.getChatRecordList();
          if (data.msgType == 3) {
            this.$message({
              type: "success",
              message: "发送图片成功"
            });

            this.sendPicDialog = false;
            this.imageUrl = "";
          }
          this.scrollContentBottom();
        }

        //获取患者发送的信息
        if (data.packageType == 4) {
          if (data.msgType == 4) {
            for (let j = 0; j < this.chatRoomMsgList.length; j++) {
              if (this.chatRoomMsgList[j].id == data.id) {
                this.chatRoomMsgList.splice(j, 1);
              }
            }
          } else {
            if (data.msgType != 7 && data.msgType != 6 && data.msgType != 8) {
              let para = {
                userId: this.friendId, //发送方id  this.$authInfo.getUser().id
                friendId: this.userImId //接收方id
              };
              this.$setWs.send(39, para);
            } else if (data.msgType == 7) {
              this.getPatientInfo();
            } else if (data.msgType == 8) {
              this.getChatRecordList();
            }
          }
          this.getChatRecordList();
          this.scrollContentBottom();
        }

        //获取患者排队列表
        if (data.packageType == 6) {
          this.lineUpPatientList = data.list;
          if (data.list.length > 0 && (this.logId == null || !this.logId)) {
            for (let i in this.lineUpPatientList) {
              if (
                this.lineUpPatientList[i].inquiryType != "3" &&
                this.lineUpPatientList[i].inquiryType != "4"
              ) {
                setTimeout(() => {
                  this.tipMusicBtn();
                }, 3000);
              }
            }
          }
        }

        //获取患者加入房间事件
        if (data.packageType == 7) {
          console.log(data, this.client, "++++++++++++++视频++++++++++++++++");
          let joinMsg = data.inquiryPatientInfoResp;
          this.patientDetailList = data.inquiryPatientInfoResp;
          this.logId = data.logId;
          this.$setStore("logId", data.logId); //设置问诊id
          this.$setStore("inquirySize", data.inquiryType); //设置问诊类型
          this.friendId = joinMsg.patientIM;
          this.userImId = joinMsg.doctorIM;
          this.inquiryPatientId = joinMsg.id;
          this.getPatientInfo();
          this.isVedioOrPic = joinMsg.inquiryType;

          let para = {
            userIm: joinMsg.doctorIM, //发送方ImId
            friendIm: joinMsg.patientIM, //接收方ImId
            logId: this.logId //本次问诊id
          };
          this.$setWs.send(38, para);

          let params = {
            userId: this.friendId, //接收方id
            friendId: this.userImId //发送方id  this.$authInfo.getUser().id
          };
          this.$setWs.send(39, params);

          this.getChatRecordList(0);
        }

        //医生与患者通用-问诊离线事件
        if (data.packageType == 9) {
          if (this.isVedioOrPic != "3" && this.isVedioOrPic != "4") {
            this.isOutline = true;
            this.finishPatient();
          }
        }

        //医生与患者通用-本次问诊结束
        if (data.packageType == 14) {
          // 本次结束的操作IM,等于自己的IM的则为自己点击的结束，否则为对方的操作
          this.isOutline = false;
          if (
            this.friendId &&
            this.friendId == data.imId &&
            this.patientDetailList.doctorIM != data.imId
          ) {
            this.finishPatient();

            this.closeTrtcRoom();
          }
        }

        //修改
        if (data.packageType == 19) {
          this.isChangeMsg = true;
        }
        if (data.packageType == 33) {
          //患者下线通知医生
          this.getPatientInfo();
        }
        if (data.packageType == 38) {
          //患者重回聊天室通知医生
        }
      }
    },
    isWithdraw(value) {
      if (value) {
        document.body.addEventListener("click", this.closeMenu);
      } else {
        document.body.removeEventListener("click", this.closeMenu);
      }
    }
  },
  created() {
    // wss://www.daylaiyy.com/consultation
    var wsuri = "wss://" + this.$global.socketName + "/websocket";
    console.log(wsuri);
    this.$setWs.initWebSocket(wsuri, this.$authInfo.webToken());
    this.webSocketMsg = this.$store.state.webSocketMsg;

    setTimeout(() => {
      this.changeOnlineState("2");
    }, 500);

    this.$store.commit('setRemotePatientInfo', {})
  },
  mounted() {
    this.ossimg();

    // 检测断网
    window.addEventListener("offline", () => {
      this.$message({
        message: "已断网,请重新连接网络",
        type: "warning"
      });
    });

    window.addEventListener("online", () => {
      console.log("网络已重新连接+++++++++++++++++++++++++++");
      setTimeout(() => {
        if (this.$authInfo.webToken()) {
          let para = {
            working: 1
          };
          this.$ajax
            .receivePatients(para)
            .then(res => {
              console.log("-----医生重新上线成功-----");
            })
            .catch(err => {
              this.$message({
                message: err.msg,
                type: "error"
              });
            });
        }
      }, 3000);
    });
  },
  methods: {
    //进入远程会诊
    enterRemoteConsult() {
      if (!this.patientList.userId) {
        this.$message({
          message: "请先接诊病人",
          type: "error"
        });
        return;
      }
      console.log('patientDetailList',this.patientDetailList)
      // this.$router.push({
      //   path: "/remoteConsult/apply",
      //   query: {
      //     isApply: true,
      //     patientId: this.patientList.userId,
      //     logId: this.logId
      //   }
      // });
      this.applyDialog = true
      this.applyQuery = {
        isApply: true,
        patientId: this.patientList.userId,
        logId: this.logId
      }
    },
    cancelBtn() {
      console.log('this.socketMsg',this.socketMsg)
      //不便重连
      let respMsg = this.patientDetailList
      this.$ajax.unSuccessfulInquiry({ id: this.logId }).then(res => {
        let data = {
          logId: this.logId, //问诊id
          patientIM: respMsg.patientIM, //患者im
          userId: respMsg.userId, //用户id
          packageCode: 200,
          packageMsg: '',
          packageType: 25,
        }
        this.$setWs.send(25, data);
        let dataF = {
          logId: this.logId,
          packageType: 13,
        }
        this.$setWs.send(13, dataF);
        this.inquiryDialog = false;

        this.$message({
          message: '已取消该接诊',
          type: 'success',
        })
      }).catch(err => {
        this.$message({
          message: err.msg,
          type: 'error',
        })
      })
    },

    initList() {
      //初始化页面数据
      this.logId = null;
      this.friendId = null;

      this.inquiryPatientId = null;
      this.patientList = {};

      this.chatRoomMsgList = [];

      sessionStorage.logId && sessionStorage.removeItem("logId");
    },
    //播放音频
    tipMusicBtn() {
      let audio = document.getElementById("dingding");
      audio.play();
    },
    openDialog(dialogName, templateType) {
      if (
        this.$global.platform("hainan") &&
        ["proposalDataDialog", "interface"].includes(dialogName)
      ) {
        this.$util.message("暂未开通，敬请期待", "warning");
        return false;
      }
      if (this.logId && this.logId != null) {
        if (dialogName == "caseHistory") {
          // 查询病历
          this.$nextTick(() => {
            if (this.$global.platform("lj")) {
              this.$refs.caseHistory.onOpen("his", this.patientList);
            } else {
              if (this.$global.isNewCase) {
                this.$refs.caseHistory.onOpen("ca", {
                  ...this.patientList,
                  id: this.logId
                });
              } else {
                this.$refs.caseHistory.onOpen("normal", {
                  caseInfo: this.patientList,
                  idCard: this.patientList.patientIdcard
                });
              }
            }
          });
        }
        /* if (dialogName == 'bodySignDialog') { //人体示意弹框
                    this.bodySignDialog = true;
                } */
        if (dialogName == "sendPicDialog") {
          //发送图片弹框
          this.imageUrl = "";
          this.sendPicDialog = true;
          this.sendPicLoading = false;
        }
        if (dialogName == "measuredDataDialog") {
          //测量数据
          this.measuredDataDialog = true;
          this.getMeasuredList();
          this.isChangeMsg = false;
        }
        if (dialogName == "picDataDialog") {
          //查询图片
          this.picDataDialog = true;
          this.getChatImages();
        }
        if (dialogName == "standardDataDialog") {
          //问诊规范
          this.standardDataDialog = true;
          this.standardActiveName = "1";
          this.getDoctorNormalConsultationList();
        }
        if (dialogName == "hisDialog") {
          //his查询
          this.$refs.hisDialog.openDialog();
        }
        if (dialogName == "finishDataDialog") {
          //结束问诊
          this.finishDataDialog = true;
          this.firstVisit = 0;
          this.finishLoading = false;
          this.getNoPrescription();
        }
        if (dialogName == "chiefComplaintDialog") {
          //主诉、现病史、既往史弹框
          this.chiefComplaintDialog = true;
          this.chiefComplaintName = templateType;

          this.chiefDialog.chiefInput = this.patientList.mainSuit || "";
          this.chiefDialog.nowInput = this.patientList.presentIllness || "";
          this.chiefDialog.pastInput =
            this.patientList.historyPresentIllness || "";

          this.chiefModelName = "0";
          this.getComplaintTemplate();
          if (this.patientList.mainSuit != "" && templateType == "1") {
            this.chiefDialog.chiefInput = this.patientList.mainSuit;
          }
          if (this.patientList.presentIllness != "" && templateType == "2") {
            this.chiefDialog.nowInput = this.patientList.presentIllness;
          }
          if (
            this.patientList.historyPresentIllness != "" &&
            templateType == "3"
          ) {
            this.chiefDialog.pastInput = this.patientList.historyPresentIllness;
          }
        }
        if (dialogName == "chiefModelDialog") {
          //主诉、现病史、既往史新增模板弹框
          this.chiefModelDialog = true;
          this.chiefModelForm.templateType = "1";
          this.chiefModelForm.templateName = "";
          this.chiefModelForm.templateDetails = "";
          this.modelId = null;
        }

        if (dialogName == "allergyHistoryDialog") {
          //过敏史弹框
          this.allergyHistoryDialog = true;
          this.isAllergyInput = this.patientList.patientAllergyDetails || "";
        }
        if (dialogName == "childOptionDialog") {
          //过敏史弹框
          this.childOptionDialog = true;
        }

        if (dialogName == "drAdviceDialog") {
          // 医嘱
          this.$refs.drAdviceDialog &&
          this.$refs.drAdviceDialog.onOpen(this.patientList);
        }

        /*** 需填写主诉+诊断的操作 ***/
        if (
          [
            "westernMedicineDialog",
            "chineseMedicineDialog",
            "proposalDataDialog"
          ].includes(dialogName)
        ) {
          if (
            this.patientList.mainSuit &&
            this.patientList.diagnosis &&
            this.patientList.presentIllness &&
            this.patientList.historyPresentIllness &&
            (this.isAllergy == 2 ||
              (this.isAllergy == 1 && this.patientList.patientAllergyDetails))
          ) {
            // 中、西药弹框
            if (
              dialogName == "westernMedicineDialog" ||
              dialogName == "chineseMedicineDialog"
            ) {
              /*** 中西药弹框 start ***/
              let drugType = "";

              if (dialogName == "westernMedicineDialog") {
                drugType = "2";
              } else {
                drugType = "1";
              }
              let data = {
                logId: this.logId,
                diagnosisArray: this.patientList.diagnosisArray,
                drugType,
                inquiryPatientId: this.inquiryPatientId
              };
              this.$refs.drugDialog.onOpen({
                data,
                isEdit: false,
                paymentMethod: this.patientList.paymentMethod
              });
            }

            if (dialogName == "proposalDataDialog") {
              //住院建议书
              if (this.isOpenProposal) {
                this.getEstablishPdf(this.logId, 1);
              } else {
                this.proposalDataDialog = true;
              }
            }
          } else {
            console.log(dialogName, "==");

            this.$message.closeAll();
            this.$message({
              type: "warning",
              message: "请先填写食物/药物过敏史、主诉、现病史、既往史、诊断"
            });
          }
        }
      } else {
        this.$message.closeAll();
        this.$message({
          message: "请先接诊病人",
          type: "error"
        });
      }

      if (dialogName == "chooseICDSearchDialog") {
        //健康指导--选择ICD检索
        this.chooseICDSearchDialog = true;
        this.ICDTypeName = "drug";
        this.healthICDSearch = "";
        this.ICDlist = [];
      }
      if (dialogName == "addPrescriptionTemplateDialog") {
        //处方历史--另存為個人模板弹框
        this.addPrescriptionTemplateDialog = true;
      }
    },
    closeDialog(dialogName) {
      if (dialogName == "westernMedicineDialog") {
        //西药弹框
        this.westernMedicineDialog = false;
        this.isWesternChinese = "";
        this.getPatientInfo();
      }
      if (dialogName == "measuredDataDialog") {
        //测量数据
        this.measuredDataDialog = false;
      }
      /* if (dialogName == 'bodySignDialog') { //人体示意弹框
                this.bodySignDialog = false;
            } */
      if (dialogName == "sendPicDialog") {
        //发送图片弹框
        this.sendPicDialog = false;
      }
      if (dialogName == "hisDialog") {
        //his查询
        this.hisDialog = false;
      }
      if (dialogName == "picDataDialog") {
        //查询图片
        this.picDataDialog = false;
      }
      if (dialogName == "proposalDataDialog") {
        //住院建议书
        this.proposalDataDialog = false;
        this.getPatientInfo();
      }
      if (dialogName == "standardDataDialog") {
        //问诊规范
        this.standardDataDialog = false;
        this.standardActiveName = "1";
        this.standardPage.current = 1;
        this.standardDrugPage.current = 1;
        this.diagnosisPage.current = 1;
      }
      if (dialogName == "finishDataDialog") {
        //结束问诊
        this.finishDataDialog = false;
        this.finishLoading = false;
      }
      if (dialogName == "standardDetailDialog") {
        //药品规范查看
        this.standardDetailDialog = false;
      }
      if (dialogName == "drugSpeciFicationDetailDialog") {
        //药品规范详情
        this.drugSpeciFicationDetailDialog = false;
      }
      if (dialogName == "chiefComplaintDialog") {
        //主诉、现病史、既往史弹框
        this.chiefComplaintDialog = false;
      }
      if (dialogName == "chiefModelDialog") {
        //主诉、现病史、既往史新增模板弹框
        this.chiefModelDialog = false;
        this.$nextTick(() => {
          this.$refs.chiefModelForm.resetFields();
        });
      }
      if (dialogName == "allergyHistoryDialog") {
        //过敏史弹框
        this.allergyHistoryDialog = false;
      }
      if (dialogName == "childOptionDialog") {
        //过敏史弹框
        this.childOptionDialog = false;
      }
      if (dialogName == "inspectionDialog") {
        //检验检查弹框
        this.inspectionDialog = false;
      }
      if (dialogName == "prescriptionInfoListDialog") {
        //处方历史--查看详情
        this.prescriptionInfoListDialog = false;
      }
      if (dialogName == "addPrescriptionDialog") {
        //处方历史--开药弹框
        this.addPrescriptionDialog = false;
        if (this.isWesternChinese == 2) {
          this.$nextTick(() => {
            this.$refs.drugClassForm.resetFields();
          });
        } else {
          this.$nextTick(() => {
            this.$refs.drugChineseForm.resetFields();
          });
        }
      }
      if (dialogName == "addPrescriptionTemplateDialog") {
        //处方历史--另存個人模板弹框
        this.addPrescriptionTemplateDialog = false;
      }
    },
    getPatientJoinRoom(item) {
      //接诊
      if (this.logId && this.logId != null) {
        this.$message({
          message: "已有接诊中的患者",
          type: "error"
        });
      } else {
        this.chatRoomMsgList = [];

        let wsPara = {
          logId: item.logId, // 问诊id，待接诊列表内已提供
          packageType: 10,
          packageCode: 200,
          packageMsg: ""
        };
        this.$setWs.send(10, wsPara);
        this.friendId = item.imId;
        this.logId = item.logId;
        this.inquiryPatientId = item.inquiryPatientId;
        this.isVedioOrPic = item.inquiryType;

        this.getPatientInfo();
        this.getChatRecordList();
      }
    },
    getPatientInfo() {
      //获取患者信息
      let para = {
        id: this.logId,
        webToken: this.$authInfo.webToken()
      };
      this.$ajax
        .getAllInfo(para)
        .then(res => {
          this.patientList = res.data || {};
          if (res.data.hospitalizationDetailResp) {
            this.isOpenProposal = true;
          } else {
            this.isOpenProposal = false;
          }
          if (this.patientList.isDrugAllergy == "1") {
            this.isAllergy = "1";
          } else {
            this.isAllergy = "2";
          }
        })
        .catch(err => {});
    },
    getQuickMsg() {
      //获取问诊规范快捷信息
      let para = {
        webToken: this.$authInfo.webToken(),
        current: 1,
        size: 0
      };
      this.$ajax
        .getDoctorNormalConsultationList(para)
        .then(res => {
          this.quickMsglist = res.data.list;
        })
        .catch(err => {
          this.$message({
            message: err.msg,
            type: "error"
          });
        });
    },
    doctorSendMsg(type, item) {
      //发送信息
      if (this.sendMsgToPatient != "" && type != "quick") {
        let data = {
          msgText: this.sendMsgToPatient, // 信息体
          msgUserName: this.patientList.doctorName,
          friendId: this.friendId, // 接收方的用户imID
          inquiryLogId: this.logId, // 本次问诊的id
          msgType: 0, // 消息类型：0文字消息、1固定表情 3 图片url
          msgDate: this.formatDate(new Date()), // 发送时间
          packageType: 3
        };
        this.$setWs.send(3, data);

        this.sendMsgToPatient = "";
      } else if (type == "quick") {
        let data = {
          msgText: item.content, // 信息体
          msgUserName: this.patientList.doctorName,
          friendId: this.friendId, // 接收方的用户imID
          inquiryLogId: this.logId, // 本次问诊的id
          msgType: 0, // 消息类型；0文字消息、1固定表情 3 图片url
          msgDate: this.formatDate(new Date()), // 发送时间
          packageType: 3
        };
        this.$setWs.send(3, data);

        this.popoverMsg = false;
      }

      this.scrollContentBottom();
    },
    // 过滤日期格式
    formatDate(date, format) {
      if (format === undefined) {
        format = "YY-MM-DD hh:mm:ss";
      }
      var year = date.getFullYear(),
        month = date.getMonth() + 1, //月份是从0开始的
        day = date.getDate(),
        hour = date.getHours(),
        min = date.getMinutes(),
        sec = date.getSeconds();
      var preArr = Array.apply(null, Array(10)).map(function(elem, index) {
        return "0" + index;
      });
      var newTime = format
        .replace(/YY/g, year)
        .replace(/MM/g, preArr[month] || month)
        .replace(/DD/g, preArr[day] || day)
        .replace(/hh/g, preArr[hour] || hour)
        .replace(/mm/g, preArr[min] || min)
        .replace(/ss/g, preArr[sec] || sec);
      return newTime;
    },
    finishPatient() {
      // 用户结束问诊--packageType状态等于14
      this.finishInquiryDialog = true;
    },
    finishInquiry() {
      // packageType状态等于14
      this.finishDataDialog = true;
      this.finishInquiryDialog = false;
      this.getNoPrescription();
    },
    handleChiefClick(tab, event) {
      //主诉、现病史、既往史tab
      this.chiefComplaintName = tab.name;
      this.chiefModelName = "0";
      this.getComplaintTemplate();
    },
    handleModelClick(tab, event) {
      //获取主诉、现病史、既往史---个人模板、公用模板tab
      this.chiefModelName = tab.name;
      this.getComplaintTemplate();
    },
    getComplaintTemplate() {
      //获取主诉、现病史、既往史模板
      let para = {
        isPersonalTemplate: this.chiefModelName,
        templateType: this.chiefComplaintName
      };

      if (this.templateNameSearch != "") {
        para.templateName = this.templateNameSearch;
      }
      this.$ajax
        .getTemplate(para)
        .then(res => {
          this.complaintTemplateList = res.data.list || [];
        })
        .catch(err => {
          this.$message({
            message: err.msg,
            type: "error"
          });
        });
    },
    quoteModel(row) {
      //引用模板
      if (row.templateType == "1") {
        this.chiefDialog.chiefInput = row.templateDetails;
      } else if (row.templateType == "2") {
        this.chiefDialog.nowInput = row.templateDetails;
      } else if (row.templateType == "3") {
        this.chiefDialog.pastInput = row.templateDetails;
      }
    },
    editModel(row) {
      //编辑模板
      this.chiefModelDialog = true;
      this.modelId = row.id;
      this.chiefModelForm.templateType = row.templateType;
      this.chiefModelForm.templateName = row.templateName;
      this.chiefModelForm.templateDetails = row.templateDetails;
    },
    delectModel(row) {
      //删除模板
      this.$confirm(`是否确认删除个人模板？`, "删除", {
        customClass: "l-confirm",
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(() => {
          this.$ajax
            .deleteTemplate({ id: row.id })
            .then(res => {
              this.getComplaintTemplate();
              this.$message({
                message: res.msg,
                type: "success"
              });
            })
            .catch(err => {
              this.$message({
                message: err.msg,
                type: "error"
              });
            });
        })
        .catch(() => {});
    },
    saveChiefComplaint() {
      //保存主诉、现病史、既往史
      let para = {
        webToken: this.$authInfo.webToken(),
        id: this.logId
      };
      para.mainSuit = this.chiefDialog.chiefInput;
      para.presentIllness = this.chiefDialog.nowInput;
      para.historyPresentIllness = this.chiefDialog.pastInput;
      this.$ajax
        .updateInquiryLog(para)
        .then(res => {
          this.$message({
            message: res.msg,
            type: "success"
          });
          this.chiefComplaintDialog = false;
          this.getPatientInfo();
        })
        .catch(err => {
          this.$message({
            message: err.msg,
            type: "error"
          });
        });
    },
    clearChief() {
      //清空主诉、现病史、既往史
      this.$confirm(`是否确认清空？`, "清空", {
        customClass: "l-confirm",
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(() => {
          if (this.chiefComplaintName == "1") {
            this.chiefDialog.chiefInput = "";
          } else if (this.chiefComplaintName == "2") {
            this.chiefDialog.nowInput = "";
          } else {
            this.chiefDialog.pastInput = "";
          }
        })
        .catch(() => {});
    },
    addChiefForm(formName) {
      //主诉、现病史、既往史新模板--新增&编辑
      this.$refs[formName].validate(valid => {
        if (valid) {
          let para = {
            webToken: this.$authInfo.webToken()
          };
          for (let key in this.chiefModelForm) {
            para[key] = this.chiefModelForm[key];
          }
          if (this.modelId) {
            para.id = this.modelId;
          }
          this.$ajax
            .newTemplate(para)
            .then(res => {
              this.$message({
                message: res.msg,
                type: "success"
              });
              this.chiefModelDialog = false;
              this.$nextTick(() => {
                this.$refs[formName].resetFields();
              });
              this.getComplaintTemplate();
            })
            .catch(err => {
              this.$message({
                message: err.msg,
                type: "error"
              });
            });
        } else {
        }
      });
    },
    updateAllergyHistory() {
      //过敏史--保存
      this.allergyLoading = true;
      let para = {
        webToken: this.$authInfo.webToken(),
        patientAllergyDetails:
          this.isAllergy == "1" ? this.isAllergyInput : "无",
        id: this.inquiryPatientId
      };
      this.$ajax
        .updateAllergyHistory(para)
        .then(res => {
          this.allergyHistoryDialog = false;
          this.allergyLoading = false;
          this.isAllergyInput = "";
          this.$message({
            message: res.msg,
            type: "success"
          });
          this.getPatientInfo();
        })
        .catch(err => {
          this.allergyLoading = false;
          this.$message({
            message: err.msg,
            type: "error"
          });
        });
    },
    updateChildOption() {
      this.childOptionDialog = false;
    },
    handleStandardClick(tab, event) {
      //问诊规范tab
      this.standardSearch = "";
      this.standardDrugSearch = "";
      this.standardDiagnosisSearch = "";
      if (tab.name == "1") {
        this.getDoctorNormalConsultationList();
      } else if (tab.name == "2") {
        this.getDrugSpeciFicationList(1);
      } else if (tab.name == "3") {
        this.getDiagnosisList();
      }
    },
    getDoctorNormalConsultationList({ page } = {}) {
      //获取问诊流程
      page && (this.standardPage.current = page);
      let para = {
        webToken: this.$authInfo.webToken(),
        current: this.standardPage.current,
        size: this.standardPage.size
      };
      if (this.standardSearch) {
        para.modelName = this.standardSearch;
      }
      this.$ajax
        .getDoctorNormalConsultationList(para)
        .then(res => {
          this.standardList = res.data.list;
          this.standardPage.total = res.data.total;
          this.standardPage.page = res.data.pages;
        })
        .catch(err => {
          this.$message({
            message: err.msg,
            type: "error"
          });
        });
    },
    changeStandardTableCurrent(val) {
      //问诊流程分页
      this.standardPage.current = val;
      this.getDoctorNormalConsultationList();
    },

    getDrugSpeciFicationList({ page } = {}) {
      //用药规范列表
      page && (this.standardDrugPage.current = page);
      let para = {
        webToken: this.$authInfo.webToken(),
        current: this.standardDrugPage.current,
        size: this.standardDrugPage.size
      };
      if (this.standardDrugSearch) {
        para.keyword = this.standardDrugSearch;
      }
      this.$ajax
        .getDrugSpeciFicationList(para)
        .then(res => {
          this.standardDrugList = res.data.list;
          this.standardDrugPage.total = res.data.total;
          this.standardDrugPage.page = res.data.pages;
        })
        .catch(err => {
          this.$message({
            message: err.msg,
            type: "error"
          });
        });
    },
    checkDrugSpeciFicationDetail(row) {
      // 用药规范--点击详情
      this.drugSpeciFicationDetailDialog = true;
      this.$ajax
        .getDrugSpeciFicationDetail({
          id: row.id,
          webToken: this.$authInfo.webToken()
        })
        .then(res => {
          this.ficationDetailList = res.data || {};
        });
    },
    checkDrugInfo(row) {
      //用药规范--点击查看
      this.standardDetailDialog = true;
      this.$ajax
        .viewDrugSpeciFication({
          id: row.id,
          webToken: this.$authInfo.webToken()
        })
        .then(res => {
          this.standardDrugDetailList = res.data || {};
        });
    },
    changeDrugTableCurrent(val) {
      //用药规范分页
      this.standardDrugPage.current = val;
      this.getDrugSpeciFicationList();
    },

    getDiagnosisList({ page } = {}) {
      // 诊断规范
      page && (this.diagnosisPage.current = page);
      let para = {
        webToken: this.$authInfo.webToken(),
        current: this.diagnosisPage.current,
        size: this.diagnosisPage.size
      };
      if (this.standardDiagnosisSearch) {
        para.diagnosisName = this.standardDiagnosisSearch;
      }
      this.$ajax
        .getDiagnosisSpeciFicationList(para)
        .then(res => {
          this.diagnosisList = res.data.list;
          this.diagnosisPage.total = res.data.total;
          this.diagnosisPage.page = res.data.pages;
        })
        .catch(err => {
          this.$message({
            message: err.msg,
            type: "error"
          });
        });
    },
    changeDiagnosisTableCurrent(val) {
      //诊断规范分页
      this.diagnosisPage.current = val;
      this.getDiagnosisList();
    },
    getICDList() {
      //获取ICD列表
      this.ICDLoading = true;
      let para = {
        webToken: this.$authInfo.webToken()
      };
      if (this.healthICDSearch) para.keyword = this.healthICDSearch;
      this.$ajax
        .getIcdList(para)
        .then(res => {
          this.ICDlist = res.data.list || [];
        })
        .catch(err => {
          this.$message({
            message: err.msg,
            type: "error"
          });
        });
    },

    getChatImages() {
      //获取患者上传的图片列表
      let para = {
        webToken: this.$authInfo.webToken(),
        logId: this.logId,
        userIm: this.patientDetailList.patientIM
      };
      this.$ajax
        .getChatImages(para)
        .then(res => {
          this.chatImages = res.data.list || [];
        })
        .catch(err => {
          this.$message({
            message: err.msg,
            type: "error"
          });
        });
    },
    getMeasuredList({ page } = {}) {
      //获取测量数据列表
      page && (this.measuredListPage.current = page);
      let para = {
        webToken: this.$authInfo.webToken(),
        size: this.measuredListPage.size,
        current: this.measuredListPage.current,
        logId: this.logId,
        identityCard: this.patientList.patientIdcard
      };
      this.$ajax
        .getMeasureDataList(para)
        .then(res => {
          this.measuredList = res.data.list || [];
          this.measuredListPage.total = res.data.total || 0;
        })
        .catch(err => {});
    },
    changeMeasuredCurrent(val) {
      //测量数据列表分页
      this.measuredListPage.current = val;
      this.getMeasuredList();
    },

    /*** 健康指导弹框 start ***/
    openHealthDialog() {
      this.$refs.healthDialog.onOpen(
        this.logId,
        this.patientList.diagnosisArray
      );
    },
    closeHealthDialog() {
      // 关闭健康指导弹框
      this.getPatientInfo();
    },
    /*** 健康指导弹框 end ***/
    addInquiryLogHospitalization() {
      //添加住院建议书

      this.$refs.proposalForm.validate(valid => {
        if (valid) {
          let para = {
            webToken: this.$authInfo.webToken(),
            hospitalizationDepartment: this.proposalForm
              .hospitalizationDepartment,
            hospitalizationHospital: this.patientList.hospitalName,
            remark: this.proposalForm.remark,
            logId: this.logId
          };
          this.$ajax
            .addInquiryLogHospitalization(para)
            .then(res => {
              this.proposalDataDialog = false;
              this.$message({
                message: res.msg,
                type: "success"
              });
            })
            .catch(err => {
              this.$message({
                message: err.msg,
                type: "error"
              });
            });
        }
      });
    },
    getNoPrescription() {
      //结束问诊--未开处方
      let para = {
        webToken: this.$authInfo.webToken()
      };
      this.$ajax.noPrescriptionList(para).then(res => {
        this.noPrescriptionList = res.data.list;
      });
    },
    async addNoPrescription() {
      //结束问诊--成功问诊
      if (
        this.finishReasonSearch == "" &&
        this.patientList.prescriptionList.length <= 0
      ) {
        this.$message({
          message: "请选择未开方原因",
          type: "error"
        });
        return false;
      }

      let paraData = {
        webToken: this.$authInfo.webToken(),
        id: this.logId
      };

      this.finishLoading = true;
      var tempWindow = await this.createNewWin();
      this.$ajax
        .endInquiry(paraData)
        .then(res => {
          this.gotoNewWin(tempWindow, res.data.esignUrl || "");

          this.finishLoading = false;
          if (this.patientList.prescriptionList.length <= 0) {
            this.endInquiry();
          } else {
            let data = {
              logId: this.logId,
              packageType: 13
            };
            this.$setWs.send(13, data);

            this.finishDataDialog = false;
            this.initList();
            this.closeTrtcRoom();

            this.$message({
              message: res.msg,
              type: "success"
            });
            this.reload(); //刷新页面
          }
        })
        .catch(err => {
          this.finishLoading = false;
          this.endInquiry();
        });
    },
    endInquiry() {
      //结束问诊
      this.finishLoading = true;
      let para = {
        webToken: this.$authInfo.webToken(),
        inquiryPatientId: this.inquiryPatientId
      };
      if (this.finishReasonSearch && this.finishReasonSearch != "") {
        para.unprescribedReasons = this.finishReasonSearch;
      }

      this.$ajax
        .addNoPrescription(para)
        .then(res => {
          this.finishLoading = false;
          let data = {
            logId: this.logId,
            packageType: 13
          };
          this.$setWs.send(13, data);
          this.finishDataDialog = false;
          this.initList();
          this.closeTrtcRoom();
          this.$message({
            message: res.msg,
            type: "success"
          });
          this.reload(); //刷新页面
        })
        .catch(err => {
          this.finishLoading = false;
          this.$message({
            message: err.msg,
            type: "error"
          });
        });
    },
    finishLog(state) {
      //结束问诊--未成功问诊
      if (
        this.firstVisit === 0 &&
        !this.finishReasonSearch &&
        (!this.patientList.prescriptionList ||
          this.patientList.prescriptionList.length <= 0)
      ) {
        this.$message({
          message: "请选择未开方原因",
          type: "error"
        });
        return;
      }

      let para = {
        webToken: this.$authInfo.webToken(),
        inquiryPatientId: this.inquiryPatientId
      };
      if (this.finishReasonSearch && this.finishReasonSearch != "") {
        para.unprescribedReasons = this.finishReasonSearch;
      }

      this.$ajax
        .addNoPrescription(para)
        .then(res => {
          this.$message({
            message: res.msg,
            type: "success"
          });
        })
        .catch(err => {
          this.$message({
            message: err.msg,
            type: "error"
          });
        });

      this.finishLoading = true;
      let data = {
        logId: this.logId,
        packageType: 13
      };
      this.$setWs.send(13, data);
      this.$ajax
        .unSuccessfulInquiry({
          id: this.logId,
          // unprescribedReasons: this.finishReasonSearch,
          firstVisit: this.firstVisit
        })
        .then(res => {
          this.finishLoading = false;

          this.finishDataDialog = false;
          this.initList();
          this.closeTrtcRoom();
        })
        .catch(err => {
          this.finishLoading = false;
          this.$util.message(err.msg);
        });
    },
    /*** 报告意见单弹框+新增申请单弹框 start ***/
    openCheckDialog(type, id = "") {
      // 打开检验检查弹框
      if (this.$refs.checkDialog) {
        this.$refs.checkDialog.onOpen({
          type,
          logId: this.logId,
          id, // 意见单ID
          userIm: this.patientDetailList.patientIM
        });
      }
    },
    getNewInspectionList() {
      // 问诊中，获取最新的检验检查列表
      this.$ajax
        .getNewInspectionList({
          logId: this.logId,
          userIm: this.patientDetailList.patientIM
        })
        .then(res => {
          this.patientList.inspectionOpinionList = res.data.list || [];
        })
        .catch(err => {
          this.patientList.inspectionOpinionList = [];
        });
    },
    closeCheckDialog(result) {
      // 关闭检验检查弹框
      if (result) {
        this.getNewInspectionList();
      }
    },
    openApplicationDialog(type, id = "", template = "") {
      // 打开申请单弹框
      if (this.$refs.applicationDialog) {
        this.$refs.applicationDialog.onOpen({
          type,
          logId: this.logId,
          id, // 意见单ID
          template
        });
      }
    },
    getNewApplicationList() {
      // 问诊中，获取最新的申请单列表
      this.$ajax
        .getNewApplicatonList({
          logId: this.logId,
          userIm: this.patientDetailList.patientIM
        })
        .then(res => {
          this.patientList.formListResult = res.data.list || [];
        })
        .catch(err => {
          this.patientList.formListResult = [];
        });
    },
    closeApplicationDialog(result) {
      // 关闭申请单弹框
      if (result) {
        this.getNewApplicationList();
      }
    },
    // 删除检验检查&申请单项目
    deleteCheckItem(type, id) {
      // type=1, 意见单
      // type=2, 申请单模板一(templateValue=inquiry_checklist_common_template)
      // type=3, 申请单模板二(templateValue=inquiry_checklist_ecg_template)
      let apiName = "";
      let tips = "";
      if (type == "advice") {
        tips = "是否要删除检查检验意见";
        apiName = "deleteInspectionOpinion";
      } else if (type == "inquiry_checklist_common_template") {
        tips = "是否要删除申请单";
        apiName = "deleteApplicationTemplateOne";
      } else if (type == "inquiry_checklist_ecg_template") {
        tips = "是否要删除申请单";
        apiName = "deleteApplicationTemplateTwo";
      }

      this.$confirm(tips, "删除", {
        customClass: "l-confirm",
        confirmButtonText: "确认",
        cancelButtonText: "取消"
      })
        .then(() => {
          this.$ajax[apiName]({ id })
            .then(res => {
              this.$message.closeAll();
              this.$message({
                type: "success",
                message: res.msg
              });

              if (type == "advice") {
                this.getNewInspectionList();
              } else if (
                type == "inquiry_checklist_common_template" ||
                type == "inquiry_checklist_ecg_template"
              ) {
                this.getNewApplicationList();
              }
              this.getPatientInfo();
            })
            .catch(err => {
              this.$message.closeAll();
              this.$message({
                type: "error",
                message: err.msg
              });
            });
        })
        .catch();
    },
    /*** 报告意见单弹框+新增申请单弹框 end ***/
    /*** 诊断弹框 start ***/
    openDiagnosisDialog(data = []) {
      if (this.logId && this.logId != null) {
        this.$nextTick(() => {
          this.$refs.diagnosisDialogComponent.onOpen({
            logId: this.logId,
            data
          });
        });
      } else {
        this.$message.closeAll();
        this.$message({
          message: "请先接诊病人",
          type: "error"
        });
      }
    },
    closeDialogComponent(flag, refName) {
      if (flag) {
        switch (refName) {
          case "diagnosisDialogComponent": // 诊断弹框
            this.getPatientInfo();
            break;
        }
      }
    },
    /*** 诊断弹框 end ***/

    getEstablishPdf(id, resourceType, templateValue) {
      //打开pdf、img
      let params = {
        id: id, //数据id
        resource: resourceType //1=生成住院建议书 2=生成健康指导 3=生成检验检查单 4=生成处方单
      };
      if (resourceType == 5) params.template = templateValue;

      params.isCancel = resourceType == 1;

      this.$refs.pdfDialog && this.$refs.pdfDialog.onOpen(params);
    },
    //分诊
    triageInquiry(item, type) {
      this.triageType = type;
      this.triageLogMsg = item;
      this.triageInquiryDialog = true;
      this.triagePatientType = item.inquiryType;
      this.departmentNameSearch = "";
      this.doctorNameSearch = "";
      this.getDepartmentList();
      this.getOnlineDoctorList();
    },
    getDepartmentList() {
      // 获取科室列表
      this.$ajax
        .getDepartmentListPc()
        .then(res => {
          this.departmentList = res.data.list;
        })
        .catch(err => {
          this.$message.closeAll();
          this.$message({
            message: err.msg,
            type: "error"
          });
        });
    },
    getOnlineDoctorList() {
      // 获取在线医生
      let para = {};
      if (this.departmentNameSearch) {
        para.departmentId = this.departmentNameSearch;
      }
      if (this.doctorNameSearch) {
        para.keyWord = this.doctorNameSearch;
      }
      this.$ajax
        .getOnlineDoctorList(para)
        .then(res => {
          if (res.data.list != []) {
            this.onlineDoctorList = res.data.list;
            for (let j = 0; j < this.onlineDoctorList.length; j++) {
              if (this.onlineDoctorList[j].id == this.$authInfo.getUser().id) {
                this.onlineDoctorList.splice(j, 1);
              }
            }
          } else {
            this.onlineDoctorList = res.data.list || [];
          }
        })
        .catch(err => {
          this.$message.closeAll();
          this.$message({
            message: err.msg,
            type: "error"
          });
        });
    },
    triagePatient(row) {
      //分诊操作
      this.$confirm(`是否确认分诊？`, "删除", {
        customClass: "l-confirm",
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(() => {
          let data = {
            // logId: this.triageLogMsg.logId, // 被分诊的问诊logId
            packageType: 15,
            dispatchedDoctorId: row.id // 被分诊的医生id
          };
          if (this.triageType == 1) {
            data.logId = this.logId;
          } else {
            data.logId = this.triageLogMsg.logId;
          }
          this.$setWs.send(15, data);
          this.triageInquiryDialog = false;
          if (this.triageType == 1) {
            this.initList();
            this.closeTrtcRoom();
          }
        })
        .catch(() => {});
    },

    openMenu(data, e) {
      //是否弹出撤回功能
      this.msgData = data;
      let x = e.layerX;
      let y = e.layerY;
      this.top = y;
      this.left = x;

      var timeNow = this.formatDate(new Date());
      var timePass = data.msgDate;
      var date1 = new Date(timePass);
      var date2 = new Date(timeNow);
      var s1 = date1.getTime(),
        s2 = date2.getTime();
      var total = (s2 - s1) / 1000;
      var day = parseInt(total / (24 * 60 * 60)); //计算整数天数
      var afterDay = total - day * 24 * 60 * 60; //取得算出天数后剩余的秒数
      var hour = parseInt(afterDay / (60 * 60)); //计算整数小时数
      var afterHour = total - day * 24 * 60 * 60 - hour * 60 * 60; //取得算出小时数后剩余的秒数

      // var min = parseInt(afterHour / 60); //计算整数分
      // var afterMin = total - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60; //取得算出分后剩余的秒数

      if (this.friendId == data.friendId) {
        if (afterHour > 120) {
          this.isWithdraw = false;
          this.$alert("消息发送已超过2分钟，不可进行撤回操作", "提示", {
            confirmButtonText: "确定",
            callback: action => {}
          });
        } else {
          this.isWithdraw = true;
        }
      } else {
        this.isWithdraw = false;
      }
    },
    withdrawHandle() {
      //撤回功能
      let data = {
        msgUserName: this.patientList.doctorName, //医生名称
        id: this.msgData.id, //信息id
        msgText: this.patientList.doctorName + "医生撤回了一条消息", // 信息体
        friendId: this.friendId, // 接收方的用户imID
        inquiryLogId: this.logId, // 本次问诊的id
        msgType: 4, // 消息类型：0文字消息、1固定表情 3 图片url 4 撤回
        msgDate: this.formatDate(new Date()), // 发送时间
        packageType: 3
      };
      this.$setWs.send(3, data);
      this.isWithdraw = false;
      this.getChatRecordList();
    },
    closeMenu() {
      //关闭撤回
      this.isWithdraw = false;
    },
    ossimg() {
      this.$ajax
        .uploadFileBridge({
          dir: "webpc/"
        })
        .then(res => {
          let { code, data } = res;
          if (code === 1) {
            this.ossParams = JSON.stringify(data);
          }
        })
        .catch(err => {
          this.$util.message(err.msg);
        });
    },
    handleChangeUpload(val, key) {
      this.imageUrl = val;
    },
    sendPic() {
      //发送图片
      if (this.imageUrl) {
        this.sendPicLoading = true;
        let data = {
          msgUserName: this.patientList.doctorName, //医生名称
          msgText: this.imageUrl, // 信息体
          friendId: this.friendId, // 接收方的用户imID
          inquiryLogId: this.logId, // 本次问诊的id
          msgType: 3, // 消息类型：0文字消息、1固定表情 3 图片url 4 撤回
          msgDate: this.formatDate(new Date()), // 发送时间
          packageType: 3
        };
        this.$setWs.send(3, data);
      } else {
        this.$message({
          message: "请选择图片发送",
          type: "error"
        });
      }
    },
    getChatRecordList(page) {
      //获取历史聊天记录
      let para = {
        friendId: this.friendId,
        userId: this.patientDetailList.doctorIM
      };
      if (page == 3) {
        para.id = this.chatRoomMsgList[0].id;
      }
      this.$ajax
        .getChatRecordList(para)
        .then(res => {
          if (page == 3) {
            let chatList = res.data.reverse();
            if (chatList.length > 0) {
              for (let i = 0; i < chatList.length; i++) {
                this.chatRoomMsgList.unshift({
                  id: chatList[i].id,
                  msgUserName: chatList[i].msgUserName,
                  msgText: chatList[i].msgText,
                  msgDate: chatList[i].msgDate,
                  msgType: chatList[i].msgType,
                  packageType: chatList[i].packageType,
                  isRead: chatList[i].isRead
                });
              }
              if (chatList.length < 20) {
                this.noHistoryChat = true;
              } else {
                this.noHistoryChat = false;
              }
            } else {
              this.noHistoryChat = true;
            }
          } else {
            this.chatRoomMsgList = res.data;
            if (this.chatRoomMsgList.length >= 20) {
              this.noHistoryChat = false;
            } else {
              this.noHistoryChat = true;
            }
          }

          if (page != 3) {
            this.scrollContentBottom();
          }
        })
        .catch(err => {
          this.$util.message(err.msg);
        });
    },
    scrollContentBottom() {
      //聊天置于底部
      this.$nextTick(() => {
        setTimeout(() => {
          let msg = document.getElementById("scrollContent"); // 获取对象
          if (msg) msg.scrollTop = msg.scrollHeight; // 滚动高度
        }, 100);
      });
    },
    changeOnlineState(type) {
      this.changeBtn = type;
      let data = {
        doctorId: this.$authInfo.getUser().id, //医生id
        isOnline: type
      };
      this.$setWs.send(31, data);
    },
    reservedInquiry() {
      // 保留问诊操作
      this.$confirm(`是否保留本次问诊？`, "保留问诊", {
        customClass: "l-confirm",
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(() => {
          this.finishInquiryDialog = false;
          let data = {
            doctorId: this.$authInfo.getUser().id, //医生id
            logId: this.logId //本次问诊id
          };
          this.$setWs.send(32, data);
          this.initList();
        })
        .catch(() => {});
    },
    finishReply() {
      //结束回复
      this.$confirm(`是否结束回复？`, "结束回复", {
        customClass: "l-confirm",
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(() => {
          let data = {
            logId: this.logId //本次问诊id
          };
          this.$setWs.send(35, data);
        })
        .catch(() => {});
    },
    handleScroll() {
      this.$nextTick(() => {
        setTimeout(() => {
          let msg = document.getElementById("scrollContent"); // 获取对象
          if (msg) msg.scrollTop = msg.scrollHeight; // 滚动高度
        }, 100);
      });
    },
    /* --- 弹框 start --- */
    onShowDialog(type) {
      switch (type) {
        case "updatePatient": // 修改患者资料弹框
          this.$refs.updatePatient &&
          this.$refs.updatePatient.onOpen(
            this.inquiryPatientId,
            this.patientList
          );
          break;
        case "payment": // 付费方式
          this.paymentCfg.visible = true;
          this.paymentLoading = false;
          this.paymentForm.paymentMethod = this.patientList.paymentMethod || "";
          this.$refs.paymentDialog && this.$refs.paymentDialog.clearValidate();
          break;
        case "disease": // 修改病种
          this.$refs.updateDisease &&
          this.$refs.updateDisease.onOpen(this.patientList);
          break;
      }
    },
    onSubmitDialog(type = "") {
      switch (type) {
        default:
          // 提价修改，更新患者数据
          this.getPatientInfo();
          break;
      }
    },
    onCloseDialog(type, isRefresh) {
      switch (type) {
        case "payment": // 付费方式
          this.paymentCfg.visible = false;
          break;
      }
    },
    submitPaymentForm() {
      // 提交付费类型修改
      this.paymentLoading = true;

      this.$refs.paymentForm.validate(valid => {
        if (valid) {
          let params = {
            logId: this.logId,
            paymentMethod: this.paymentForm.paymentMethod
          };

          this.$ajax
            .updatePaymentMethodByZh(params)
            .then(res => {
              this.paymentLoading = false;
              this.paymentCfg.visible = false;

              this.$message({
                type: "success",
                message: res.msg
              });

              this.getPatientInfo();
            })
            .catch(err => {
              this.paymentLoading = false;
              this.$message.closeAll();
              this.$message.error(err.msg);
            });
        } else {
          this.paymentLoading = false;
        }
      });
    },
    /* --- 弹框 end --- */
    linkTo(key) {
      switch (key) {
        case "interface":
          if (!this.logId) {
            this.$util.message("请先接诊病人");
          } else {
            // window.location.href = "SSOPluginsFile.myp://"
            let routeUrl = this.$router.resolve({
              path: "/interface"
            });

            window.open(routeUrl.href, "_blank");
          }
          break;
      }
    },
    closeTrtcRoom() {
      if (this.$global.isTrtc) {
        this.$refs.trtcVideo.leaveRoom();
      } else {
        this.$refs.agoraVideo.leave();
      }
    },
    async createNewWin() {
      var tempWindow = null;
      if (await this.$util.notSilentCa()) {
        tempWindow = window.open("", "_blank");
        tempWindow.document.title = "e签宝(加载中,请勿关闭)";
      }
      return tempWindow;
    },
    gotoNewWin(tempWindow, url = "") {
      if (!tempWindow) return;
      if (url) {
        tempWindow.location.href = url;
      } else {
        tempWindow && tempWindow.close();
      }
    }
  }
};
